package com.topideal.supplychain.hades.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.stream.FileImageInputStream;
import javax.xml.bind.DatatypeConverter;

import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.StringUtils;

/**
 * java实现AES256加密解密
 * 
 */

public class ASE256Util {

	private static final Logger logger = Logger.getLogger(ASE256Util.class);

	private static final String KEY = "*:@3%7!a):14frfrtq1;'1";

	private static final String PASSWORD = "q3r44k'67l4h;6,9t.'6'7.;0";

	public static String encrypt(String content) {
		if (StringUtils.isEmpty(content)) {
			return content;
		}
		try {
			// "AES"：请求的密钥算法的标准名称
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			// 256：密钥生成参数；securerandom：密钥生成器的随机源

			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(PASSWORD.getBytes());
			kgen.init(256, secureRandom);
			// 生成秘密（对称）密钥
			SecretKey secretKey = kgen.generateKey();
			// 返回基本编码格式的密钥
			byte[] enCodeFormat = secretKey.getEncoded();

			// 根据给定的字节数组构造一个密钥。enCodeFormat：密钥内容；"AES"：与给定的密钥内容相关联的密钥算法的名称
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			// 将提供程序添加到下一个可用位置
			Security.addProvider(new BouncyCastleProvider());
			// 创建一个实现指定转换的 Cipher对象，该转换由指定的提供程序提供。
			// "AES/ECB/PKCS7Padding"：转换的名称；"BC"：提供程序的名称
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] byteContent = content.getBytes("utf-8");
			byte[] cryptograph = cipher.doFinal(byteContent);
			return DatatypeConverter.printBase64Binary(cryptograph);
		} catch (Exception e) {
			logger.error("加密失败", e.getCause());
			logger.error(e);
		}
		return content;
	}

	public static String encrypt128(String content) {
		if (StringUtils.isEmpty(content)) {
			return content;
		}
		try {
			// "AES"：请求的密钥算法的标准名称
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			// 256：密钥生成参数；securerandom：密钥生成器的随机源

			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(PASSWORD.getBytes());
			kgen.init(128, secureRandom);
			// 生成秘密（对称）密钥
			SecretKey secretKey = kgen.generateKey();
			// 返回基本编码格式的密钥
			byte[] enCodeFormat = secretKey.getEncoded();

			// 根据给定的字节数组构造一个密钥。enCodeFormat：密钥内容；"AES"：与给定的密钥内容相关联的密钥算法的名称
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			// 将提供程序添加到下一个可用位置
			Security.addProvider(new BouncyCastleProvider());
			// 创建一个实现指定转换的 Cipher对象，该转换由指定的提供程序提供。
			// "AES/ECB/PKCS7Padding"：转换的名称；"BC"：提供程序的名称
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] byteContent = content.getBytes("utf-8");
			byte[] cryptograph = cipher.doFinal(byteContent);
			return DatatypeConverter.printBase64Binary(cryptograph);
		} catch (Exception e) {
			logger.error("加密失败", e.getCause());
			logger.error(e);
		}
		return content;
	}
	
	public static String decrypt128(String cryptograph) {
		if (StringUtils.isEmpty(cryptograph)) {
			return cryptograph;
		}
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(PASSWORD.getBytes());
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] content = cipher.doFinal(DatatypeConverter.parseBase64Binary(cryptograph));
			return new String(content, "UTF-8");
		} catch (Exception e) {
			logger.error("解密失败", e);
		}
		return cryptograph;
	}
	
	
	public static String decrypt(String cryptograph) {
		if (StringUtils.isEmpty(cryptograph)) {
			return cryptograph;
		}
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(PASSWORD.getBytes());
			kgen.init(256, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] content = cipher.doFinal(DatatypeConverter.parseBase64Binary(cryptograph));
			return new String(content, "UTF-8");
		} catch (Exception e) {
			logger.error("解密失败", e);
		}
		return cryptograph;
	}

	public static byte[] tohash256Deal(String datastr) throws NoSuchAlgorithmException {
		MessageDigest digester = MessageDigest.getInstance("SHA-256");
		digester.update(datastr.getBytes());
		byte[] hex = digester.digest();
		return hex;
	}

	public static String encryptPic(String filePath) throws IOException {
		String wayBillPic = null;
		FileImageInputStream input = null;
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			input = new FileImageInputStream(new File(filePath));
			
			byte[] buf = new byte[1024];
			int numBytesRead = 0;
			while ((numBytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, numBytesRead);
			}
			wayBillPic = encrypt(new String(output.toByteArray(),"ISO-8859-1"));
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			output.close();
			input.close();
		}
		return wayBillPic;
	}

	/*public static void main(String[] args) {

		String content = "BaESU72JKrgn";
		String encryptResult = ASE256Util.encrypt(content);
		
		String encryptResult2 = ASE256Util.encrypt128(content);

		System.out.println(encryptResult);
		System.out.println(encryptResult2);

		String decryptResult = ASE256Util.decrypt(encryptResult);

		String decryptResult2 = ASE256Util.decrypt128(encryptResult2);
		System.out.println(decryptResult);
		System.out.println(decryptResult2);
	}*/
}
